<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Config;
use app\common\library\Auth;


/**
 * 个人中心接口
 */
class My extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
    }  

      /**
     * 修改用户信息
     * @param string $avatar
     * @param string $nickname
     */
    public function edit(){
        $user = $this->auth->getUser();
        $avatar = input('avatar');
        $nickname = input('nickname');
     
        if($avatar){
            $user->avatar = $avatar;
        }
        if($nickname){
            $user->nickname = $nickname;
        }
        $user->save();
        $this->success('修改成功');
    }
    
    /**
     * 会员信息
     * @ApiMethod   (GET)
     */
    public function index()
    {
        $userInfo = $this->auth->getUserinfo();
        
        $this->success('会员信息', $userInfo);
    }
     /**
     * 关注和取消关注阿婆主
     * @param int $user_id
     * @param int $status 0的时候为取消关注
     */
     public function follow(){
        $follow_old = Db::name('user')->where(['id'=>$this->user_id])->value('follow');

        // 关注
        if(input('status')){
            $follow_array = explode(',', rtrim($follow_old,','));

            $key = array_search(input('user_id'), $follow_array);
            if ($key !== false)$this->error('请勿重复关注');
            $follow_new = $follow_old.input('user_id').',';
            Db::name('user')->where(['id'=>$this->user_id])->update(['follow'=>$follow_new]);

            // 阿婆主增加粉丝数
            $fans = Db::name('user')->where(['id'=>input('user_id')])->value('fans');
            $new_fans = $fans.$this->user_id.',';
            Db::name('user')->where(['id'=>input('user_id')])->update(['fans'=>$new_fans]);

            $this->success('关注成功');

        // 取消关注
        }else{

            $follow_array = explode(',', rtrim($follow_old,','));

            $key = array_search(input('user_id'), $follow_array);
            if ($key !== false){
                if(!input('status')){
                    unset($follow_array[$key]);
                    $follow_new = implode(',', $follow_array).',';

                     $fans = Db::name('user')->where(['id'=>input('user_id')])->value('fans');
                     $fans_array = explode(',', $fans);
                     $fans_key = array_search(input('user_id'), $fans_array);
                     unset($fans_array[$fans_key]);
                     $fans_new = implode(',', $fans_array);
                     
                     $res2 =  Db::name('user')->where(['id'=>$this->user_id])->update(['follow'=>$follow_new]);
                     $res3 = Db::name('user')->where(['id'=>input('user_id')])->update(['fans'=>$fans_new]);

                    if($res2&&$res3)$this->success('取消关注成功');
                }
            }

        }
        
     }

     /**
     * 已关注阿婆主列表
     */
     public function follow_list(){
        $follow = Db::name('user')->where(['id'=>$this->user_id])->value('follow');
        $return = [];
        if($follow){
            $follow_array = explode(',', rtrim($follow,','));
            $return = Db::name('user')->where('id','in',$follow_array)->field('id,avatar,nickname')->select();
        }
        $this->success('关注列表',$return);
     }
     /**
     * 查看阿婆主信息 is_follow是否关注过,fans_num是粉丝数,follow_num关注数量
     * @param int $user_id
     * @param int $type 根据分区筛选对应的稿件
     */
    public function member_data()
    {
        $return['userInfo'] = Db::name('user')->field('id,avatar,nickname,fans,follow')->where(['id'=>input('user_id')])->find();
       
        $follow = Db::name('user')->where('id',$this->user_id)->value('follow');
        if($follow){
            $follow = explode(',', rtrim($follow,','));
            if(in_array(input('user_id'), $follow)){
                $return['is_follow'] = 1;
            }else{
                $return['is_follow'] = 0;
            }
        }else{
            $return['is_follow'] = 0;
        }
        $fans = $return['userInfo']['fans'];
        if($fans){
            $return['fans_num'] = count(explode(',', trim($fans,',')));
        }else{
            $return['fans_num'] = 0;
        }
        $follow = $return['userInfo']['follow'];
        if($follow){
            $return['follow_num'] = count(explode(',', trim($follow,',')));
        }else{
            $return['follow_num'] = 0;
        }

        $return['manuscript'] = Db::name('manuscript as m')->join('user u','m.user_id = u.id')->field("m.*,FROM_UNIXTIME(m.createtime,'%Y-%m-%d %H:%i:%s') as createtime,u.avatar")->where(['m.type'=>input('type'),'user_id'=>input('user_id')])->order('m.createtime desc')->select();

        foreach ($return['manuscript'] as $key => $value) {
          $collect_array = json_decode($value['collect_array'],true);
          if(!empty($collect_array)){
            if(in_array($this->user_id,$collect_array )){
              $return['manuscript'][$key]['is_collect'] = 1;
            }else{
              $return['manuscript'][$key]['is_collect'] = 0;
            }
          }else{
            $return['manuscript'][$key]['is_collect'] = 0;
          }
          $dianzan_array = json_decode($value['dianzan_array'],true);
          if(!empty($dianzan_array)){
            if(in_array($this->user_id,$dianzan_array )){
              $return['manuscript'][$key]['is_dianzan'] = 1;
            }else{
              $return['manuscript'][$key]['is_dianzan'] = 0;
            }
          }else{
            $return['manuscript'][$key]['is_dianzan'] = 0;
          }
        }
        
        $this->success('查看其他会员信息', $return);
    }
     /**
     * 历史记录
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/my/history)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     */
    public function history(){
        
        $cource_id = Db::name('user')->where(['id'=>$this->user_id])->value('history');

        $data = Db::name('manuscript')->field('title,images,id')->where('id','in',$cource_id)->select();

        $this->success('请求成功',$data);
    }

    /**
     * 获取我的稿件列表
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_manuscript)
     */
    public function my_manuscript()
    {
        $my_manuscript = Db::name('manuscript')->where(['user_id'=>$this->user_id])->select();

        $this->success('获取我的稿件列表',$my_manuscript);
    }

    /**
     * 获取我的收藏列表（两种情况，要么有数据，要么就提示列表为空）
     * @ApiSummary  
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_collect)
     */
    public function my_collect()
    {
        $collect = Db::name('collect')->where(['user_id'=>$this->user_id])->value('collect');
        $collect = json_decode($collect,true);
        if(empty($collect))$this->error('列表为空');
        $collect = implode(',', $collect);
        $list = Db::name('manuscript')->where('id','in',$collect)->field("id,title,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->order('createtime desc')->select();
        $this->success('获取我的收藏列表（两种情况，要么有数据，要么就提示列表为空）',$list);
    }

    /**
     * 获取我的点赞列表（两种情况，要么有数据，要么就提示列表为空）
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/my/my_dianzan)
     * @ApiReturn   ({
     })
     */
    public function my_dianzan()
    {
        $dianzan = Db::name('dianzan')->where(['user_id'=>$this->user_id])->value('dianzan');
        $dianzan = json_decode($dianzan,true);
        if(empty($dianzan))$this->error('列表为空');
        $dianzan = implode(',', $dianzan);
        $list = Db::name('manuscript')->where('id','in',$dianzan)->field("id,title,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->order('createtime desc')->select();
        $this->success('获取我的点赞列表（两种情况，要么有数据，要么就提示列表为空）',$list);
    }


}
